import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/resources/routers.dart';
import 'package:smart_freezer/core/service/api/app_api.dart';
import 'package:smart_freezer/core/service/service/net_service.dart';
import 'package:smart_freezer/core/utils/logs.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';
import 'package:smart_freezer/generated/locale_keys.g.dart';

class BarcodeScannerWithController extends StatefulWidget {
  const BarcodeScannerWithController({Key? key}) : super(key: key);

  @override
  _BarcodeScannerWithControllerState createState() =>
      _BarcodeScannerWithControllerState();
}

class _BarcodeScannerWithControllerState
    extends State<BarcodeScannerWithController>
    with SingleTickerProviderStateMixin {

  String? barcode;

  MobileScannerController scannerController = MobileScannerController(
    torchEnabled: false,   // 闪关灯
    formats: [BarcodeFormat.qrCode]  //
    // facing: CameraFacing.front,  // 后置摄像头
  );


  bool isStarted = true;

  TextEditingController _codeController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Builder(
        builder: (context) {
          return Stack(
            children: [
              MobileScanner(
                controller: scannerController,
                fit: BoxFit.contain,
                allowDuplicates: false,   // 允许重复扫描
                onDetect: (barcode, args) {  // 扫描结果
                  setState(() {
                    // this.barcode = barcode.rawValue;
                    _codeController.text = barcode.rawValue ?? "";
                  });

                  if (!mounted) return;
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text(_codeController.text),  // 扫描成功
                      backgroundColor: Colors.green,
                      duration: Duration(milliseconds: 2000),
                    ),
                  );

                },
              ),

              Positioned(
                top: MainCommon.statusBarHeight,
                child: Container(
                  width: MainCommon.screenWidth,
                  height: MainCommon.appBarHeight,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      InkWell(
                        onTap: () {
                          Get.back();
                        },
                        child: Container(
                          width: 50,
                          child: Icon(Icons.chevron_left, color: Colors.white, size: 30,)
                        ),
                      ),

                      Text(LocaleKeys.add_device_name.trc(), style: TextStyle(color: Colors.white, fontSize: 20),),

                      InkWell(
                        onTap: () async {
                          final ImagePicker _picker = ImagePicker();
                          // Pick an image
                          final XFile? image = await _picker.pickImage(
                            source: ImageSource.gallery,
                          );

                          if (image != null) {
                            final foundCode = await scannerController.analyzeImage(image.path) as bool;
                            logs("图片: ${image.path} $foundCode");

                            if (foundCode) {
                              if (!mounted) return;
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(
                                  content: Text('Success'),  // 扫描成功
                                  backgroundColor: Colors.green,
                                  duration: Duration(milliseconds: 2000),
                                ),
                              );

                            } else {
                              if (!mounted) return;
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(
                                  content: Text('Fail'),  // 扫描失败, 请重试!
                                  backgroundColor: Colors.red,
                                  duration: Duration(milliseconds: 2000),
                                ),
                              );
                            }
                          }
                        },
                        child: Container(
                          // width: 50,
                          padding: EdgeInsets.symmetric(horizontal: 5),
                          child: Text(LocaleKeys.add_device_album.trc(), style: TextStyle(color: Colors.white, fontSize: 17,),)
                        ),
                      )
                    ],
                  ),
                )
              ),

              Positioned(
                bottom: 40,
                child: Container(
                  width: MainCommon.screenWidth,
                  alignment: Alignment.bottomCenter,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        width: 200,
                        height: 40,
                        child: TextField(
                          controller: _codeController,

                          decoration: InputDecoration(
                            hintText: LocaleKeys.add_device_add_tip.trc(),
                            contentPadding: EdgeInsets.fromLTRB(10, 0, 0, 0),  // TF宽高间距
                            enabledBorder: OutlineInputBorder(),
                            focusedBorder: OutlineInputBorder(
                              // borderRadius: BorderRadius.circular(10),
                              // borderSide: BorderSide(color: Colors.grey, width: 1),
                            ),
                            filled: true,
                            hintStyle: TextStyle(color: Colors.grey),
                            fillColor: Colors.white,
                          ),
                          style: TextStyle(color: Colors.grey),
                          cursorColor: Colors.grey,
                        ),
                      ),

                      SizedBox(width: 5,),
                      InkWell(
                        onTap: (){
                          if(_codeController.text.isNotEmpty) {
                            _bindProduct(_codeController.text);
                          }else{
                            SmartDialog.showToast("${LocaleKeys.device_info_bianhao.trc()}${LocaleKeys.other_no_data.trc()}");
                          }

                        },
                        child: Container(
                          // width: 50,
                          height: 40,
                          padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: Color(0xFF234485),
                            borderRadius: BorderRadius.circular(3),
                          ),
                          child: Text(LocaleKeys.add_device_confirm.trc(), style: TextStyle(color: Colors.white),),
                        ),
                      ),

                    ],
                  ),
                ),

              ),

            ],
          );
        },
      ),
    );
  }

  // 添加设备
  _bindProduct(String serialNumber) async {
    ResultData data = await AppApi.getInstance().bindProduct({"serialNumber": serialNumber});
    if(data.code == 0) {
      Get.toNamed(LCRouter.home_add_device);
    }else{
      SmartDialog.showToast(data.msg);
    }
  }

}

/*
Align(
                alignment: Alignment.bottomCenter,
                child: Container(
                  alignment: Alignment.bottomCenter,
                  height: 100,
                  color: Colors.black.withOpacity(0.4),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      IconButton(
                        color: Colors.white,
                        icon: ValueListenableBuilder(
                          valueListenable: controller.torchState,
                          builder: (context, state, child) {
                            if (state == null) {
                              return const Icon(
                                Icons.flash_off,
                                color: Colors.grey,
                              );
                            }
                            switch (state as TorchState) {
                              case TorchState.off:
                                return const Icon(
                                  Icons.flash_off,
                                  color: Colors.grey,
                                );
                              case TorchState.on:
                                return const Icon(
                                  Icons.flash_on,
                                  color: Colors.yellow,
                                );
                            }
                          },
                        ),
                        iconSize: 32.0,
                        onPressed: () => controller.toggleTorch(),
                      ),
                      IconButton(
                        color: Colors.white,
                        icon: isStarted
                            ? const Icon(Icons.stop)
                            : const Icon(Icons.play_arrow),
                        iconSize: 32.0,
                        onPressed: () => setState(() {
                          isStarted ? controller.stop() : controller.start();
                          isStarted = !isStarted;
                        }),
                      ),
                      Center(
                        child: SizedBox(
                          width: MediaQuery.of(context).size.width - 200,
                          height: 50,
                          child: FittedBox(
                            child: Text(
                              barcode ?? 'Scan something!',
                              overflow: TextOverflow.fade,
                              style: Theme.of(context)
                                  .textTheme
                                  .headline4!
                                  .copyWith(color: Colors.white),
                            ),
                          ),
                        ),
                      ),
                      IconButton(
                        color: Colors.white,
                        icon: ValueListenableBuilder(
                          valueListenable: controller.cameraFacingState,
                          builder: (context, state, child) {
                            if (state == null) {
                              return const Icon(Icons.camera_front);
                            }
                            switch (state as CameraFacing) {
                              case CameraFacing.front:
                                return const Icon(Icons.camera_front);
                              case CameraFacing.back:
                                return const Icon(Icons.camera_rear);
                            }
                          },
                        ),
                        iconSize: 32.0,
                        onPressed: () => controller.switchCamera(),
                      ),
                      IconButton(
                        color: Colors.white,
                        icon: const Icon(Icons.image),
                        iconSize: 32.0,
                        onPressed: () async {
                          final ImagePicker _picker = ImagePicker();
                          // Pick an image
                          final XFile? image = await _picker.pickImage(
                            source: ImageSource.gallery,
                          );
                          if (image != null) {
                            if (await controller.analyzeImage(image.path)) {
                              if (!mounted) return;
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(
                                  content: Text('Barcode found!'),
                                  backgroundColor: Colors.green,
                                ),
                              );
                            } else {
                              if (!mounted) return;
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(
                                  content: Text('No barcode found!'),
                                  backgroundColor: Colors.red,
                                ),
                              );
                            }
                          }
                        },
                      ),
                    ],
                  ),
                ),
              ),


 */
